package com.fly.util;

import org.apache.commons.lang3.StringUtils;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.concurrent.atomic.AtomicLong;

/**
 * Created by frinder on 2018/3/9.
 */
@Component
public class SidService {

    final static DateTimeFormatter FORMATTER = DateTimeFormatter.ofPattern("yyMMddHHmm");

    private final AtomicLong counter = new AtomicLong(0);

    private final int maxValue = 9999;

    @Scheduled(cron = "0 1 0 * * ?")
    public void resetCounter() {
        counter.set(0L);
    }

    public enum Biz {
        //
        CUSTOMER("C"),
        //
        EMPLOYEE("E"),
        //
        CARD("C"),
        //
        PRODUCT("P"),

        //
        SYS_COLUMNS("SC"),

        //
        ROLE("SO"),
        //
        AUTHORITY("SA"),
        //
        RESOURCE("SR");

        private String name;

        Biz(String name) {
            this.name = name;
        }
    }

    /**
     * @param biz
     * @return
     */
    public String getSid(Biz biz) {
        if (counter.get() > maxValue) {
            counter.set(0);
        }
        return String.format("%s%s%s",
                biz.name,
                LocalDateTime.now().format(FORMATTER),
                StringUtils.leftPad(String.valueOf(counter.incrementAndGet()), 4, "0")
        );
    }
}
